package com.yc.web;

import com.yc.dao.DBHelper;
import com.yc.bean.ShoeOrder;
import com.yc.bean.User;
import com.yc.web.model.CartItem;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Set;

public class OrderBiz {

    public int order(ShoeOrder order, Set<CartItem> cartItems, User user) throws Exception {
        if (cartItems==null || cartItems.size()<=0){
            throw new RuntimeException("订单为空....");
        }

        int result = 0;

        DBHelper db = new DBHelper();
        Integer oid = 0;
        //事务处理：
        Connection con = db.getConnection();
        try {
            con.setAutoCommit(false);       //关闭隐式事务提交

            String sql = "insert into shoeorder( userid , tel, address,ordertime,ps) values (?,?,?,now(),?)";
            PreparedStatement pstmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);//RETURN_GENERATED_KEYS代表获取自动生成的id
            pstmt.setString(1, user.getUserid() +"");
            pstmt.setString(2, order.getTel());
            pstmt.setString(3, order.getAddress());
            pstmt.setString(4, order.getPs());
            pstmt.executeUpdate();
            //取自动生成的id
            ResultSet rs = pstmt.getGeneratedKeys();
            if (rs.next()) {
                oid = rs.getInt(1);
            }

            //循环所有的订单项，添加到数据表resorderitem
            String sql2 = "insert into resorderitem (oid,sid,dealprice,num) values (?,?,?,?)";
            for (CartItem ci : cartItems) {
                pstmt = con.prepareStatement(sql2);
                pstmt.setString(1, oid + "");
                pstmt.setString(2, ci.getShoes().getSid() + "");
                pstmt.setString(3, ci.getShoes().getSprice() + "");
                pstmt.setString(4, ci.getNum() + "");
                pstmt.executeUpdate();
            }
            con.commit();   //事务提交
        }catch ( Exception e){
            if (con!=null){
                con.rollback();
            }
            throw e;
        }finally {
            if (con!=null){
                con.close();
            }
        }
        return result;
    }
}
